package pais.www.stat;

import java.io.PrintWriter;
import java.util.StringTokenizer;

import pais.db.*;
import papos.rowset.KeyNameNotFoundException;
import papos.rowset.StorageSystem;
import pasys.error.PaposException;

class PrintUrlStat {
  public static void printUrlStat(PrintWriter toClient, StringTokenizer stok) throws PaposException  {
    toClient.println("printing url stat.");
    long invalidURLCount = 0;
    long totalConnFailCount = 0;
    long connFailURLCount = 0;
    long notYetIndexedCount = 0;
    long parseErrorCount =0;
    long count = 0;
    HtmlPageTable pageTable = HtmlPageTable.getInstance();
    HtmlPage page = new HtmlPage();
    StorageSystem storage = pageTable.getStorage();
    try {
      if (storage.findFirst("UID_", page)) {
        do {
          int connFailCountOfPage = page.getConnectFailCount();
          if ( connFailCountOfPage > 0 ) {
            totalConnFailCount += connFailCountOfPage;
            connFailURLCount++;
          }

          if (page.getChangeDate() == HtmlPage.NULL_CHANGE_DATE) {
            notYetIndexedCount ++;
          }

          if ( page.getChangeDate() == HtmlPage.INVALUD_URL_CHANGE_DATE ) {
            invalidURLCount ++;
          }

          if ( page.getChangeDate() == HtmlPage.HTML_PARSER_ERROR_CHANGE_DATE ) {
            parseErrorCount ++;
          }

          count++;
        } while (storage.findNext("UID_", page));

        long indexedCount = count - (notYetIndexedCount + invalidURLCount+parseErrorCount);

        toClient.println("total url count = "+count);
        toClient.println("indexed url count,% = "+indexedCount+", "+percent(indexedCount,count)+"%");
        toClient.println("not yet indexed url count,% = "+notYetIndexedCount+", "+percent(notYetIndexedCount,count)+"%");
        toClient.println("invalid url count,% = "+invalidURLCount+", "+percent(invalidURLCount,count)+"%");
        toClient.println("parse error url count,% = "+parseErrorCount+", "+percent(parseErrorCount,count)+"%");
        toClient.println("connection fail url count = "+connFailURLCount+", "+percent(connFailURLCount,count)+"%");
        if ( connFailURLCount > 0 )
          toClient.println("average connection fails per connection fail url = "+ (double)totalConnFailCount/(double)connFailURLCount);

        long totalKeyCount = PAISSystemTable.getInstance().getSystem(PAISSystemTable.PAIS_SYSTEM_ID).getNextKID();
        if ( indexedCount > 0 )
          toClient.println("average keyword count per url = "+ (double) totalKeyCount / (double) indexedCount );
      }

    } catch (KeyNameNotFoundException e) {
      assert(false);
    }
  }

  public static int percent(long sub, long total) {
    return (int) (sub * 100 / total); 
  }
}
